package com.kedacom.config;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

import org.springframework.beans.SimpleTypeConverter;

import com.kedacom.config.annotation.ConfigProperty;
import com.kedacom.config.resource.ConfigurationResource;

public abstract class AbstractConfiguration implements Configuration {

	private SimpleTypeConverter typeConverter = new SimpleTypeConverter();
	
	@Override
	public void loadConfiguration(ConfigurationResource resource) throws IllegalArgumentException, IllegalAccessException {
		for (Field field : this.getClass().getDeclaredFields()) {
			if (!field.isAccessible()) { // 如果变量不可访问（变量为私有等），设置变量的访问权限
				field.setAccessible(true);
			}
			ConfigProperty configProperty = field.getAnnotation(ConfigProperty.class);
			if (configProperty != null) {
				if (Modifier.isStatic(field.getModifiers())) {
					throw new IllegalStateException("@ConfigProperty annotation is not supported on static fields");
				}
				
				String key = configProperty.value().length() <= 0 ? field.getName() : configProperty.value();
				Object value = resource.getValue(key);
				if (value != null) {
					Object _value = typeConverter.convertIfNecessary(value, field.getType());
					field.set(this, _value);
				}
			}
		}
	}
}
